package swing;

import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.util.Vector;
import java.io.Serializable;

/**
 * 创建表格演示
 * @author fidel
 */
public class CreateTableDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame form = new JFrame("Create Table");
            form.setVisible(true);
            form.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            form.setSize(600, 400);
            form.setLocationRelativeTo(null);
            form.getContentPane().setLayout(new GridLayout(2, 2));
            form.getContentPane().add(new JTable(10, 5));
            Vector<Vector<Serializable>> v1 = new Vector<>();
            for (int i = 0; i < 5; i++) {
                v1.addElement(createVector());
            }
            Vector<String> v2 = new Vector<>();
            for (int j = 1; j <= 8; j++) {
                v2.addElement("第" + j + "列");
            }
            JTable table1 = new JTable(v1, v2);
            form.getContentPane().add(new JScrollPane(table1));
            JScrollPane scrollPane = new JScrollPane();
            JTable table2 = new JTable(v1, v2);
            scrollPane.setViewportView(table2);
            form.getContentPane().add(scrollPane);
            JPanel panel = new JPanel();
            form.getContentPane().add(panel);
            panel.setLayout(new BorderLayout());
            JTable table3 = new JTable(new Integer[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }, new String[] { "第一列", "第二列", "第三列", "第四列" });
            panel.add(table3.getTableHeader(), BorderLayout.NORTH);
            panel.add(table3, BorderLayout.CENTER);
        });
    }

    private static Vector<Serializable> createVector() {
        Vector<Serializable> v = new Vector<>();
        v.addElement(false);
        v.addElement((short) 0);
        v.addElement(new Random().nextInt());
        v.addElement(-(new Random().nextLong()));
        v.addElement(new Random().nextFloat());
        v.addElement(-(new Random().nextDouble()));
        v.addElement('c');
        v.addElement("String");
        return v;
    }
}
